<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use DB;
use Hash;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\Http\Requests\UserFromPostRequest;

class UserController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function getIndex()
    {
        //数据分页
        $users = DB::table('user')->paginate(15);

        return view('Admin.user.index',['users'=>$users]);
    }

    /**
     * 后台用户添加方法
     *
     * @return view 用户添加表单
     */
    public function getAdd()
    {
        //解析模板
        return view('Admin.user.add');
    }

    public function postInsert(UserFromPostRequest $request)
    {
         //只提取部分数据
        $date = $request->except('_token');

        // 调用方法进行头像的上传操作
        $date['pic'] = $this->upload($request);

        //哈希加密
        $date['password'] = Hash::make($date['password']);
        //将数据添加到数据库
        $res = DB::table('user')->insert($date);

        if($res){
            //重定向到user/index
            return redirect('admin/user/index')->with('success','用户添加成功');
        }else{
            //回到上个页面
            return back()->with('error','用户添加失败');
        }


    }

    //文件上传操作
        public function upload($request)
        {
             //检测是否有文件上传
            if ($request->hasFile('pic')) {
    //          //随机文件名
                $name = md5(time()+rand(1,99999));
                //后缀名
                $su = $request->file('pic')-> getClientOriginalExtension(); 
                $request->file('pic')->move('./public/uploads', $name.'.'.$su);
                return '/public/uploads/'.$name.'.'.$su;

               }
        }

        public function postDel(Request $request)
        {
            //获取数据
            $id = $request->input('id');

            //执行删除
            $res = DB::table('user')->where('id','=',$id)->delete();
            echo $res;



        }

        //用户修改
        public function getEdit($id)
        {
            //根据id查询用户信息
            $users = DB::table('user')->where('id',$id)->first();
            
            return view('Admin.user.edit',['users'=>$users]);
        }

        //执行用户数据修改
        public function postUpdate(Request $request)
        {
            $data = $request->all();
            if($request->hasFile('pic')){
                $data['pic'] = $this->upload($request);
            }

            //执行修改

            $res = DB::table('user')->where('id',$data['id'])->update($data);
            if($res){
                return redirect('admin/user/index')->with('success','用户修改成功');
            }else{
                return back()->with('error','用户修改失败');
            }
    }
}
